<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">

              <el-table-column label="序号" width="120">
                <template #default="{$index}">
                  <!-- 真正的序号应该是
                  之前页面(前一页)的所有数据长度开始 +1 +2 +3 ... -->
                  {{ (page.page-1) * page.pagesize + $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="别想改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <el-dialog :title="`${dialogTitle}角色`" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <el-tree
          ref="permTree"
          :data="permList"
          :props="{label: 'name'}"
          default-expand-all
          :show-checkbox="true"
          check-strictly

          node-key="id"
        />
        <template #footer>
          <el-row type="flex" justify="center">
            <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-row>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {
  getCompanyInfo,
  getRoleList,
  delRole,
  getRoleDetail,
  updateRole,
  addRole,
  assignPermission
} from '@/api/setting'
import { getPermission } from '@/api/permission'
import { listToTreeData } from '@/utils'
export default {
  data() {
    return {
      formData: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      roleList: [],
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },

      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      showPermDialog: false,
      permList: [],
      roleId: ''
    }
  },
  computed: {
    dialogTitle() {
      return this.roleForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
    this.getPermission()
  },
  methods: {
    async getPermission() {
      const res = await getPermission()
      this.permList = listToTreeData(res.filter(e => e.enVisible === '1'), '0')
    },
    async assignPerm(id) {
      this.roleId = id
      const { permIds } = await getRoleDetail(id)
      this.showPermDialog = true
      this.$nextTick(() => {
        console.log(permIds)
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    async btnPermOK() {
      const data = {
        id: this.roleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      }
      // 发请求
      await assignPermission(data)
      // 提示用户
      this.$message.success('修改成功')
      // 关闭弹窗
      this.showPermDialog = false
    },
    btnPermCancel() {
      // 清空数据
      this.$refs.permTree.setCheckedKeys([])
      // 关闭弹窗
      this.showPermDialog = false
    },

    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      this.page.total = total
      console.log(this.roleList)
    },
    currentChange(newPage) {
      // 1. 修改页码配置
      this.page.page = newPage
      // 2. 发请求
      this.getRoleList()
    },
    async delRole(id) {
      try {
        // 二次询问
        await this.$confirm('是否确认删除?')
        // 请求
        await delRole(id)

        // 加载数据
        // 删除完毕更新数据,
        // 更新前如果只剩下一条更新后肯定就没了
        // 应该判断长度,翻页(如果已经翻到第一页就不在翻页)
        if (this.roleList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.getRoleList()
        // 提示用户
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async btnOK() {
      try {
        // 校验表单
        await this.$refs.roleForm.validate()
        // 发送请求
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        // 提醒用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.showDialog = false
        // 更新页面
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel() {
      // 1. 清空表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 2. 清空校验
      this.$refs.roleForm.resetFields()
      // 3. 关闭弹窗
      this.showDialog = false
    },
    async editRole(id) {
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    }
  }
}
</script>

<style>

</style>
